package com.maxd.service.student;

import com.google.common.collect.Lists;
import com.maxd.adapter.LoginUserHolder;
import com.maxd.bean.PageRes;
import com.maxd.error.ExceptionEnum;
import com.maxd.model.OrderPartnerInfo;
import com.maxd.model.StudentInfo;
import com.maxd.model.UserInfo;
import com.maxd.respository.StudentInfoRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.AssertUtil;
import com.maxd.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class StudentService {

    @Autowired
    private StudentInfoRepository studentInfoRepository;

    @Autowired
    private UserRepository userRepository;

    public void save(StudentInfo student) {
        // 校验用户是否存在
        Long userId = student.getUserId();
        UserInfo userById = userRepository.getUserById(userId);
        AssertUtil.notNull(userById, ExceptionEnum.USER_NOT_FIND);
        student.setUserPhone(userById.getPhone());
        if(student.getId() != null) {
            student.setUpdateTime(new Date());
            student.setUpdateBy(LoginUserHolder.getAdminId());
        } else {
            student.setCreateBy(LoginUserHolder.getAdminId());
            student.setUpdateBy(LoginUserHolder.getAdminId());
        }
        studentInfoRepository.save(student);
    }

    public PageRes<StudentInfo> queryPage(Integer pageNo, Integer pageSize, String name) {
        // 分页参数
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
        Specification<StudentInfo> queryCondition = buildCondition(name);
        Page<StudentInfo> pageList = studentInfoRepository.findAll(queryCondition, pageable);
        log.info("分页查询到学员信息为:{}", JsonUtils.toJsonString(pageList));
        return new PageRes<>(pageList.getTotalElements(), pageList.getContent());
    }

    public List<StudentInfo> queryList(String name) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Specification<StudentInfo> queryCondition = buildCondition(name);
        List<StudentInfo> studentInfos = studentInfoRepository.findAll(queryCondition, sort);
        log.info("查询到学员信息为:{}", JsonUtils.toJsonString(studentInfos));
        return studentInfos;
    }

    private Specification<StudentInfo> buildCondition(String name) {

        log.info("查询学员信息，查询条件: name = {}", name);

        Specification<StudentInfo> queryCondition = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNotEmpty(name)) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return queryCondition;
    }

}
